import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Popconfirm, Space, Card, Tag, Pagination, Typography } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, SyncOutlined, SearchOutlined } from '@ant-design/icons';
import './ChineseEnglishCorrespondence.css';
import OperationNavBar from '../components/OperationNavBar';

const { Title, Text } = Typography;

const ChineseEnglishCorrespondence: React.FC = () => {
  const [correspondenceList, setCorrespondenceList] = useState<any[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [searchKey, setSearchKey] = useState('');
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取API基础URL
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
  
  // 获取token，实际项目中可能从localStorage或其他地方获取
  const token = localStorage.getItem('token') || 'mock-token';

  // 获取中英文对照列表
  const fetchCorrespondenceList = async (page = 1, ps = 10, key = '') => {
    setLoading(true);
    try {
      const response = await fetch(`${apiBaseUrl}/-/bin.ceCorrespondence.get_ce_correspondence`, {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify({ page, ps, key })
      });
      
      const data = await response.json();
      if (data.code === 200) {
        setCorrespondenceList(Array.isArray(data.data) ? data.data : []);
        setPagination({
          ...pagination,
          current: page,
          total: data.total || 0
        });
      } else {
        message.error(data.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('获取中英文对照列表失败:', error);
      message.error('获取数据失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchCorrespondenceList(pagination.current, pagination.pageSize, searchKey);
  }, []);

  // 新增中英文对照
  const addCorrespondence = async (values: any) => {
    try {
      const response = await fetch(`${apiBaseUrl}/-/bin.ceCorrespondence.add_ce_correspondence`, {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify(values)
      });
      
      const data = await response.json();
      if (data.code === 0 || data.code === 200) {
        message.success('添加成功');
        setIsModalVisible(false);
        form.resetFields();
        fetchCorrespondenceList(1, pagination.pageSize, searchKey);
      } else {
        message.error(data.msg || '添加失败');
      }
    } catch (error) {
      console.error('添加中英文对照失败:', error);
      message.error('添加失败，请检查网络连接');
    }
  };

  // 更新中英文对照
  const updateCorrespondence = async (values: any) => {
    try {
      const response = await fetch(`${apiBaseUrl}/-/bin.ceCorrespondence.update_ce_correspondence_by_id`, {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify({ ...values, id: editingId })
      });
      
      const data = await response.json();
      if (data.code === 0 || data.code === 200) {
        message.success('更新成功');
        setIsModalVisible(false);
        form.resetFields();
        setEditingId(null);
        fetchCorrespondenceList(1, pagination.pageSize, searchKey);
      } else {
        message.error(data.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新中英文对照失败:', error);
      message.error('更新失败，请检查网络连接');
    }
  };

  // 删除中英文对照
  const deleteCorrespondence = async (id: string) => {
    try {
      const response = await fetch(`${apiBaseUrl}/-/bin.ceCorrespondence.delete_ce_correspondence_by_id`, {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify({ id })
      });
      
      const data = await response.json();
      if (data.code === 0 || data.code === 200) {
        message.success('删除成功');
        fetchCorrespondenceList(1, pagination.pageSize, searchKey);
      } else {
        message.error(data.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除中英文对照失败:', error);
      message.error('删除失败，请检查网络连接');
    }
  };

  // 处理表单提交
  const handleSubmit = (values: any) => {
    if (editingId) {
      updateCorrespondence(values);
    } else {
      addCorrespondence(values);
    }
  };

  // 编辑操作
  const handleEdit = (record: any) => {
    setEditingId(record.id);
    form.setFieldsValue({
      en: record.en,
      cn: record.cn
    });
    setIsModalVisible(true);
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    fetchCorrespondenceList(page, pageSize || pagination.pageSize, searchKey);
  };

  // 处理搜索
  const handleSearch = () => {
    fetchCorrespondenceList(1, pagination.pageSize, searchKey);
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => (pagination.current - 1) * pagination.pageSize + index + 1
    },
    {
      title: '英文',
      dataIndex: 'en',
      key: 'en',
      render: (text: string) => <Tag color="blue">{text}</Tag>
    },
    {
      title: '中文',
      dataIndex: 'cn',
      key: 'cn',
      render: (text: string) => <Tag color="green">{text}</Tag>
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (record: any) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这条记录吗？"
            onConfirm={() => deleteCorrespondence(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="ce-correspondence-container">
      {/* 运行管理导航条 */}
      <OperationNavBar />
      <Card className="ce-correspondence-card">
        <div className="ce-correspondence-header">
          <div className="ce-correspondence-title">
            <Title level={4}>中英文对照管理</Title>
            <Text type="secondary">管理系统中使用的中英文术语对照</Text>
          </div>
          <div className="ce-correspondence-actions">
            <Space>
              <Input
                placeholder="输入关键词搜索"
                value={searchKey}
                onChange={e => setSearchKey(e.target.value)}
                onPressEnter={handleSearch}
                prefix={<SearchOutlined />}
                allowClear
              />
              <Button type="primary" onClick={handleSearch} icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={() => {
                  setEditingId(null);
                  form.resetFields();
                  setIsModalVisible(true);
                }}
              >
                新增
              </Button>
              <Button 
                icon={<SyncOutlined />} 
                onClick={() => fetchCorrespondenceList(pagination.current, pagination.pageSize, searchKey)}
              >
                刷新
              </Button>
            </Space>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={correspondenceList}
          rowKey="id"
          pagination={false}
          loading={loading}
          className="ce-correspondence-table"
        />

        <div className="ce-correspondence-pagination">
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            onChange={handlePageChange}
            showQuickJumper
            showSizeChanger
            showTotal={total => `共 ${total} 条数据`}
          />
        </div>
      </Card>

      <Modal
        title={editingId ? "编辑中英文对照" : "新增中英文对照"}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="en"
            label="英文"
            rules={[{ required: true, message: '请输入英文术语' }]}
          >
            <Input placeholder="请输入英文术语" />
          </Form.Item>
          <Form.Item
            name="cn"
            label="中文"
            rules={[{ required: true, message: '请输入中文术语' }]}
          >
            <Input placeholder="请输入中文术语" />
          </Form.Item>
          <Form.Item className="form-buttons">
            <Button type="default" onClick={() => setIsModalVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ChineseEnglishCorrespondence; 